<?php
/*
*All rights reserved: Json.
*Links:http://www.liyaoquan.cn.
*Links:http://imarkchina.cn.
*Links:http://www.imarkchina.cn.
*/

/**
 * 博客后台数据操作模型，负责数据，增，删，改，查
 * 因为没有博客数据没使用数据库，所以没有继承 Model 类
 */
Class GetbackupModel extends PublicModel{

	/**
	 * 数据备份处理
	 */
	Public function BackUPAll(){
		if (file_exists(ROOT_PATH.'/backup.zip')) {
			unlink(ROOT_PATH.'/backup.zip');
		}
		$zip = new PclZip('backup.zip');
		if (is_array($zip->create(ROOT_PATH, PCLZIP_OPT_REMOVE_PATH,ROOT_PATH))) {
			return true;
		}
	}

	/**
	 * 数据还原处理
	 */
	Public function RePlayAll(){
		if (!file_exists(ROOT_PATH.'/backup.zip')) {
			return false;
		}
		$file = ROOT_PATH.'/backup.zip';
		$zip = new PclZip($file);
		$zip->extract(PCLZIP_OPT_PATH, ROOT_PATH);
		$check = $zip->extract(PCLZIP_OPT_SET_CHMOD, 0777);
		if (is_array($check) && unlink(ROOT_PATH.'/backup.zip')) {
			return true;
		}
	}

	/**
	 * 检查更新
	 */
	Public function Check(){
		if (!is_dir(ROOT_PATH.'/Public/Upgrade/')) {
			mkdir(ROOT_PATH.'/Public/Upgrade/', 0777);
		}
		$config = $this->blogConfig();
		$pathlist_str = file_get_contents(C('upgradeurl'));
		$pathlist = $allpathlist = array();
		$key = -1;
			//获取压缩包列表
		preg_match_all("/\"(updata_[\w_]+\.zip)\"/", $pathlist_str, $allpathlist);
		$allpathlist = $allpathlist[1];
		foreach($allpathlist as $k => $v) {
			if(strstr($v, 'updata_'.C('versiontime'))) {
				$key = $k;
				break;
			}
		}
		$key = $key < 0 ? 9999 : $key;
		if ($key == 9999) {
			return false;
		}
		foreach($allpathlist as $k => $v) {
			if($k >= $key) {
				$pathlist[$k] = $v;
			}
		}
		session('upgrade', $pathlist);
		$asarray = array();
		foreach ($pathlist as $k => $v) {
			$asarray[$v] = substr($v, -12, -4);
		}
		$redata['localver'] = C('version');
		$redata['localtime'] = C('versiontime');
		$redata['netver'] = $asarray;
		return $redata;
	}

	/**
	 * 更新博客
	 */
	Public function UPGrade(){
		$pathlist = session('upgrade');
		foreach($pathlist as $k => $v) {
			$upgradezip_url = C('upgradeurl').$v;
			$upgradezip_path = ROOT_PATH.'/Public/Upgrade/'.$v;
			file_put_contents($upgradezip_path, file_get_contents($upgradezip_url));
			$zip = new PclZip($upgradezip_path);
			$zip->extract(PCLZIP_OPT_PATH, ROOT_PATH);
			unlink($upgradezip_path);
		}
		return true;
	}
}